package com.yhzl.two.shop.controller;


import com.yhzl.two.shop.common.Const;
import com.yhzl.two.shop.common.ResponseCode;
import com.yhzl.two.shop.common.ServerResponse;
import com.yhzl.two.shop.entity.User;
import com.yhzl.two.shop.service.IUserService;
import com.yhzl.two.shop.vo.UpdatePwdVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chsm
 * @since 2018-09-04
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private final IUserService userService;

    @Autowired
    public UserController(IUserService userService) {
        this.userService = userService;
    }

    @PostMapping("/login")
    public ServerResponse<User> login(@RequestBody User user, @ApiIgnore HttpSession session) {
        ServerResponse<User> loginUser = userService.login(user);
        // 登录成功将用户对象放入session,并将密码设置为null
        if (ResponseCode.SUCCESS.getCode() == userService.login(user).getStatus()) {
            session.setAttribute(Const.LOGIN_USER, loginUser.getData().setPassword(null));
        }
        return userService.login(user);
    }

    @PostMapping("/register")
    public ServerResponse<String> register(@RequestBody User user) {
        return userService.register(user);
    }

    @GetMapping("/user")
    public ServerResponse<User> getUserInfo(HttpSession session) {
        User user = (User) session.getAttribute(Const.LOGIN_USER);
        return ServerResponse.createSuccessData("获取登录信息成功", user);
    }

    @GetMapping("/front/checkPwd")
    public ServerResponse<String> checkPwd(String pwd, @SessionAttribute(Const.LOGIN_USER) User user) {
        return userService.checkPwd(user.getId(), pwd);
    }

    @PutMapping("/front/updatePwd")
    public ServerResponse<String> updatePwd(@RequestBody UpdatePwdVo updatePwdVo, @SessionAttribute(Const.LOGIN_USER) User user) {
        return userService.updatePwd(user.getId(), updatePwdVo);
    }

    /**
     * 退出登录
     * @param session
     * @return  退出信息
     */
    @GetMapping("/exit")
    public ServerResponse<String> exit(HttpSession session) {
        session.removeAttribute(Const.LOGIN_USER);
        return ServerResponse.createSuccessMessage("退出登录成功");
    }

    @PutMapping("/front/user")
    public ServerResponse<User> updateUser(@RequestBody User user, @SessionAttribute(Const.LOGIN_USER) User loginUser) {
        // 校验信息合法性
        if (!loginUser.getId().equals(user.getId())) {
            return ServerResponse.createErrorMessage("非法操作!");
        }
        return userService.updateUser(user);
    }

    @GetMapping("/checkUsername")
    public ServerResponse<String> checkUsername(String username) {
        return userService.checkUsername(username);
    }

}

